package com.sh.shanhuo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.media.MediaSelector;
import com.example.media.bean.MediaSelectorFile;
import com.example.media.resolver.Contast;
import com.sh.shanhuo.R;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.bean.UploadImageBean;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CircleImageView;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class AddPersonalInfoActivity extends BaseActivity {

    private String account;
    private String password;
    private CircleImageView image;
    private String imageUrl = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_personal_info;
    }

    @Override
    protected void initData() {
        super.initData();
        getBundle();
        findViewById(R.id.back).setOnClickListener(v -> ScreenSwitch.finish(this));
        TextView accountText = findViewById(R.id.accountText);
        TextView emailTips = findViewById(R.id.emailTips);
        TextView phoneTips = findViewById(R.id.phoneTips);
        accountText.setText(new StringBuilder().append("个人登录账号为：").append(account).append("  请牢记！"));
        EditText nickName = findViewById(R.id.nickName);
        EditText email = findViewById(R.id.email);
        EditText phone = findViewById(R.id.phone);

        //noinspection deprecation
        phone.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                return "1234567890".toCharArray();
            }
        });
        email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!TextUtils.isEmpty(email.getText().toString()) && !Tools.isEmail(email.getText().toString())) {
                    emailTips.setText("邮箱格式错误！");
                    emailTips.setTextColor(getResources().getColor(R.color.error, null));
                } else {
                    emailTips.setText("填写密码丢失后的找回邮箱！");
                    emailTips.setTextColor(getResources().getColor(R.color.text_tips, null));
                }
            } else {
                emailTips.setText("填写密码丢失后的找回邮箱！");
                emailTips.setTextColor(getResources().getColor(R.color.text_tips, null));
            }
        });
        phone.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!TextUtils.isEmpty(phone.getText().toString()) && phone.getText().toString().length() != 11) {
                    phoneTips.setText("手机号验证错误！");
                    phoneTips.setTextColor(getResources().getColor(R.color.error, null));
                } else {
                    phoneTips.setText("手机号能帮您找回丢失的账号！");
                    phoneTips.setTextColor(getResources().getColor(R.color.text_tips, null));
                }
            } else {
                phoneTips.setText("手机号能帮您找回丢失的账号！");
                phoneTips.setTextColor(getResources().getColor(R.color.text_tips, null));
            }
        });
        image = findViewById(R.id.image);
        LinearLayout imageLayout = findViewById(R.id.imageLayout);
        imageLayout.setOnClickListener(v -> {
            MediaSelector.MediaOptions mediaOptions = new MediaSelector.MediaOptions();
            //是否要显示拍照功能
            mediaOptions.isShowCamera = true;
            //是否要压缩
            mediaOptions.isCompress = true;
            //是否要显示视频文件
            mediaOptions.isShowVideo = false;
            //设置module主题
            mediaOptions.themeColor = R.color.black;
            //设置要不要裁剪（视频不裁剪、单图选择接受裁剪，裁剪大小自己可以设置）
            mediaOptions.isCrop = true;
            mediaOptions.cropWidth = 100;
            mediaOptions.cropHeight = 100;
            MediaSelector.with(AddPersonalInfoActivity.this).setMediaOptions(mediaOptions).openMediaActivity();
        });
        findViewById(R.id.complete).setOnClickListener(v -> {
            if (nickName.getText().toString().isEmpty() ||
                    email.getText().toString().isEmpty() ||
                    phone.getText().toString().isEmpty()) {
                Toast.makeText(AddPersonalInfoActivity.this, "请完善注册资料", Toast.LENGTH_SHORT).show();
            } else if ("邮箱格式错误！".contentEquals(emailTips.getText())) {
                Toast.makeText(AddPersonalInfoActivity.this, "邮箱格式错误！", Toast.LENGTH_SHORT).show();
            } else if ("手机号验证错误！".contentEquals(phoneTips.getText())) {
                Toast.makeText(AddPersonalInfoActivity.this, "手机号验证错误！", Toast.LENGTH_SHORT).show();
            } else {
                register(nickName.getText().toString().trim(),
                        email.getText().toString().trim(),
                        phone.getText().toString().trim());
            }
        });
        findViewById(R.id.jump).setOnClickListener(v -> register("", "", ""));
    }

    private void register(String nickName, String phone, String email) {
        onShowLoading();
        String UUID = Tools.getUniquePsuedoID();
        Map<String, String> params = new HashMap<>();
        params.put("userName", account);
        params.put("password", password);
        params.put("nickName", nickName);
        params.put("headUrl", imageUrl);
        params.put("phone", phone);
        params.put("email", email);
        params.put("uuid", UUID);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.ADD_USER, params, new GsonObjectCallback<BaseBean>() {
            @Override
            public void onUi(BaseBean baseBean) {
                onDismissLoading();
                if (baseBean.getCode() == 200 && "操作成功".equals(baseBean.getMsg())) {
                    Toast.makeText(AddPersonalInfoActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    ScreenSwitch.finish(AddPersonalInfoActivity.this, null, RESULT_OK);
                    return;
                }
                Toast.makeText(AddPersonalInfoActivity.this, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                onDismissLoading();
                Toast.makeText(AddPersonalInfoActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getBundle() {
        Intent intent = getIntent();
        if (intent == null)
            return;
        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;
        account = bundle.getString("account", "");
        password = bundle.getString("password", "");
    }

    /**
     * 选择图片结果回调
     *
     * @param requestCode 请求code
     * @param resultCode  结果回调code
     * @param data        数据回调
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Contast.CODE_RESULT_MEDIA && requestCode == Contast.CODE_REQUEST_MEDIA) {
            List<MediaSelectorFile> mediaList = MediaSelector.resultMediaFile(data);
            MediaSelectorFile file = mediaList.get(0);
            Glide.with(this).load(file.filePath).into(image);
            onShowLoading();
            OkHttpUtil.getInstance().postFile(OkHttpUtil.IP + OkHttpUtil.UPLOAD_IMAGE, new File(file.filePath), new GsonObjectCallback<UploadImageBean>() {
                @Override
                public void onUi(UploadImageBean uploadImageBean) {
                    onDismissLoading();
                    imageUrl = uploadImageBean.getUrl();
                }

                @Override
                public void onFailed(Call call, IOException e) {
                    Toast.makeText(AddPersonalInfoActivity.this, "上传头像失败", Toast.LENGTH_SHORT).show();
                    onDismissLoading();
                }
            });
        }
    }
}
